package mysql

//  dao/mysql/post.go
import (
	"bluebell/models"
	"errors"
	"strings"

	"github.com/jmoiron/sqlx"
)

// GetPostsByKeyword 根据关键字查询帖子（标题或内容包含关键字）
func GetPostsByKeyword(keyword string) ([]*models.Post, error) {
	var posts []*models.Post

	// 使用LIKE进行模糊匹配，%表示任意字符
	sqlStr := `SELECT 
        post_id, title, content, author_id, community_id, create_time
        FROM post 
        WHERE title LIKE ? OR content LIKE ?
        ORDER BY create_time DESC
        LIMIT 10`

	searchPattern := "%" + keyword + "%"
	err := db.Select(&posts, sqlStr, searchPattern, searchPattern)
	if err != nil {
		return nil, err
	}

	return posts, nil
}

// CreatePost 创建帖子
func CreatePost(p *models.Post) (err error) {
	sqlStr := `insert into post(
	post_id, title, content, author_id, community_id)
	values (?, ?, ?, ?, ?)
	`
	_, err = db.Exec(sqlStr, p.ID, p.Title, p.Content, p.AuthorID, p.CommunityID)
	return
}

// GetPostById 根据id查询单个贴子数据
func GetPostById(pid int64) (post *models.Post, err error) {
	post = new(models.Post)
	sqlStr := `select
	post_id, title, content, author_id, community_id, create_time
	from post
	where post_id = ?
	`
	err = db.Get(post, sqlStr, pid)
	return
}

// PostExists 检查帖子是否存在
func PostExists(postID int64) (bool, error) {
	var count int
	sqlStr := `SELECT COUNT(1) FROM post WHERE post_id = ?`
	err := db.Get(&count, sqlStr, postID)
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

// GetPostList 查询帖子列表函数
func GetPostList(page, size int64) (posts []*models.Post, err error) {
	sqlStr := `select 
	post_id, title, content, author_id, community_id, create_time
	from post
	ORDER BY create_time
	DESC
	limit ?,?
	`
	posts = make([]*models.Post, 0, 2) // 不要写成make([]*models.Post, 2)
	err = db.Select(&posts, sqlStr, (page-1)*size, size)
	return
}

// GetPostListByIDs 根据给定的id列表查询帖子数据
func GetPostListByIDs(ids []string) (postList []*models.Post, err error) {
	sqlStr := `select post_id, title, content, author_id, community_id, create_time
	from post
	where post_id in (?)
	order by FIND_IN_SET(post_id, ?)
	`
	// https: //www.liwenzhou.com/posts/Go/sqlx/
	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return nil, err
	}
	query = db.Rebind(query)
	err = db.Select(&postList, query, args...) // !!!!!!
	return
}

// DeletePost 删除帖子
func DeletePost(postId int64) (err error) {
	sqlstr := `delete from post where Post_id = ?`
	_, err = db.Exec(sqlstr, postId)
	if err != nil {
		return err
	}
	return nil
}

// GetPostByTitle 用帖子标题模糊查询
func GetPostsByTitle(title string) ([]*models.Post, error) {
	var posts []*models.Post
	// 修改 SQL 查询语句以支持模糊匹配
	sqlStr := `SELECT post_id, title, content, author_id, community_id FROM post WHERE title LIKE ?`
	// 使用 % 符号进行模糊匹配
	searchTitle := "%" + title + "%"
	err := db.Select(&posts, sqlStr, searchTitle)
	if err != nil {
		return nil, err
	}
	return posts, nil
}

// GetPostListByCommunityID 根据社区ID分页查询帖子
func GetPostListByCommunityID(communityID int64, page, size int64) ([]*models.Post, error) {
	// 计算偏移量（page从1开始）
	offset := (page - 1) * size

	// 构建分页SQL
	sqlStr := `
        SELECT post_id, title, content, author_id, community_id, create_time
        FROM post
        WHERE community_id = ?
        ORDER BY create_time DESC 
        LIMIT ? OFFSET ?
    `

	// 执行查询
	var postList []*models.Post
	err := db.Select(&postList, sqlStr, communityID, size, offset)
	return postList, err
}

// GetPostsByUserID 根据用户ID查询帖子列表
func GetPostsByUserID(userID int64) ([]*models.Post, error) {
	var posts []*models.Post
	sqlStr := `SELECT post_id, title, content, author_id, community_id, create_time
	FROM post
	WHERE author_id = ?
	ORDER BY create_time DESC`
	err := db.Select(&posts, sqlStr, userID)
	return posts, err
}

// DeletePostByUserID 删除指定用户ID和帖子ID的帖子
func DeletePostByUserID(userID, postID int64) (err error) {
	// 开始事务
	tx, err := db.Beginx()
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			tx.Rollback()
			return
		}
		err = tx.Commit()
	}()

	// 1. 删除 user_post_history 表中的相关记录
	sqlStrHistory := `DELETE FROM user_post_history WHERE post_id = ?`
	result, err := tx.Exec(sqlStrHistory, postID)
	if err != nil {
		return err
	}

	// 2. 删除 post 表中的帖子
	sqlStrPost := `DELETE FROM post WHERE post_id = ? AND author_id = ?`
	result, err = tx.Exec(sqlStrPost, postID, userID)
	if err != nil {
		return err
	}

	// 检查是否删除了帖子
	rows, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if rows == 0 {
		return errors.New("帖子不存在或用户无权限")
	}

	return nil
}
